<template>
  <view v-if="open" style="overflow: auto">
    <u-navbar
      :placeholder="true"
      :titleStyle="{ color: '#ffffff' }"
      leftIconColor="#ffffff"
      bgColor="#3775cb"
      :autoBack="true"
    >
      <template #right>
        <view @click="submitForm">
          <up-text color="#ffffff" text="提交"></up-text>
        </view>
      </template>
    </u-navbar>

    <view
      style="
        margin: 25rpx;
        background-color: #ffffff;
        padding: 15rpx 15rpx 15rpx 15rpx;
        border-radius: 15rpx;
      "
    >
      <u--form labelPosition="left" :model="formData" :rules="{}" ref="form" labelWidth="68">
        <u-form-item :borderBottom="true" label="商机名称" prop="name" ref="item1">
          <u--input v-model="formData.name" border="none"></u--input>
        </u-form-item>
        <u-form-item :borderBottom="true" label="预计金额" prop="needAmount" ref="item1">
          <u--input v-model="formData.needAmount" border="none"></u--input>
        </u-form-item>
        <u-form-item :borderBottom="true" label="预计成交" prop="predictMakeTime" ref="item1">
          <u-cell-group :border="false">
            <u-cell
              :border="false"
              :isLink="true"
              :title="formData.predictMakeTime ? convertTimestamp(formData.predictMakeTime) : ''"
              @click="
                () => {
                  if (!formData.predictMakeTime) {
                    formData.predictMakeTime = new Date().getTime()
                  }
                  show = true
                }
              "
            ></u-cell>
          </u-cell-group>
        </u-form-item>

        <u-form-item :borderBottom="true" label="销售阶段" prop="saleStageId" ref="item1">
          <u-cell-group :border="false">
            <u-cell
              :border="false"
              :isLink="true"
              :title="formData.saleStageId ? formData?.saleStageLabel : ''"
              @click="
                () => {
                  showSaleStage = true
                }
              "
            ></u-cell>
          </u-cell-group>
        </u-form-item>
        <u-form-item :borderBottom="true" label="成交几率" prop="probability" ref="item1">
          <u-slider
            style="width: 100%"
            v-model="formData.probability"
            :showValue="true"
            activeColor="#3c9cff"
            inactiveColor="#c0c4cc"
          ></u-slider>
        </u-form-item>
      </u--form>
      <u-datetime-picker
        :show="show"
        v-model="formData.predictMakeTime"
        @cancel="show = false"
        @confirm="show = false"
        :closeOnClickOverlay="true"
        :formatter="formatter"
        mode="datetime"
      ></u-datetime-picker>
      <view
        v-if="!customerId"
        @click="openSelectCus"
        style="padding: 20rpx 30rpx; background-color: #f7f7f7; margin: 15rpx 0"
      >
        <text style="padding-top: 14rpx; font-size: 26rpx; width: 450rpx">
          选择客户{{ formData!.customerLabel ? '：' + formData!.customerLabel : '' }}
        </text>
        <CusPicker
          v-model:labels="formData!.customerLabel"
          v-model="formData!.customerId"
          ref="cusPicker"
        />
      </view>

      <view>
        <u-popup :show="showSaleStage" @close="showSaleStage = false">
          <view style="padding: 20rpx">
            <u-radio-group v-model="formData.saleStageId" iconPlacement="right" placement="column">
              <u-radio
                :customStyle="{ marginBottom: '8px' }"
                v-for="(item, index) in saleStageList"
                :key="index"
                :label="item.label"
                :name="item.saleStageId"
                @change="changeFollowWay"
              >
              </u-radio>
            </u-radio-group>
          </view>
        </u-popup>
      </view>
    </view>
    <view
      style="
        margin: 25rpx;
        background-color: #ffffff;
        padding: 15rpx 15rpx 15rpx 15rpx;
        border-radius: 15rpx;
      "
    >
      <!--商品-->
      <view style="margin-bottom: 15rpx; display: flex; justify-content: space-between">
        <text>商品</text>
        <text style="margin-top: 10rpx">
          <u-icon @click="addProd" size="18" name="plus-circle"></u-icon>
        </text>
      </view>
      <prod-picker ref="prodRef" @select="selectProd" />

      <u-line></u-line>
      <view>
        <view class="cart-list">
          <uni-swipe-action>
            <uni-swipe-action-item
              v-for="item in cartList"
              :key="item.productItemId"
              class="cart-swipe"
            >
              <!-- 商品信息 -->
              <view class="goods">
                <navigator
                  :url="`/pages/goods/goods?id=${item.productId}`"
                  hover-class="none"
                  class="navigator"
                >
                  <image mode="aspectFill" class="picture" :src="item.imageUrl"></image>
                  <view class="meta">
                    <view class="name ellipsis">{{ item?.productName }}</view>
                    <view class="attrsText ellipsis">{{ item?.sku }}</view>
                    <view class="price">{{ item?.nowPrice }}</view>
                  </view>
                </navigator>
                <view class="count">
                  <u-number-box
                    v-model="item.qty"
                    :name="item.productItemId"
                    step="1"
                    :min="1"
                    @change="changeQty"
                  />
                </view>
              </view>
              <!-- 右侧删除按钮 -->
              <template #right>
                <view class="cart-swipe-right">
                  <button @tap="handleDeleteCartList(item)" class="button delete-button">
                    删除
                  </button>
                </view>
              </template>
            </uni-swipe-action-item>
          </uni-swipe-action>
        </view>
        <u-empty v-show="cartList.length === 0" mode="car" />
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import CusPicker from '@/components/customer/cus-picker.vue'
import { getSaleStageListAPI } from '@/services/common'
import ProdPicker from '@/components/product/prod-picker.vue'
import { getOpportunityAPI, postOpportunityAPI, putOpportunityAPI } from '@/services/opportunity'

const cusPicker = ref<InstanceType<typeof CusPicker>>()
const prodRef = ref<InstanceType<typeof ProdPicker>>()

// 接收页面参数
const query = defineProps<{
  fromPage: string
  customerId: string | number
  opportunityId: string
}>()
const open = ref(false)
const show = ref(false)
const showSaleStage = ref(false)
const formData = ref<any>({
  opportunityId: undefined,
  name: undefined,
  customerId: undefined,
  saleId: undefined,
  saleStageId: undefined,
  saleStageLabel: undefined,
  needAmount: undefined,
  predictMakeTime: undefined,
  payAmount: undefined,
  makeTime: undefined,
  probability: 80,
})
const formatter = (type: any, value: any) => {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  return value
}
const convertTimestamp = (timestamp: any) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = date.getMonth() + 1 // getMonth() 返回的月份从0开始，所以需要加1
  const day = date.getDate()
  const hours = date.getHours()
  const minutes = date.getMinutes()
  // 格式化输出
  return `${year}年${month}月${day}日${hours}时${minutes}分`
}

const saleStageList = ref<any[]>()

const cartList = ref<any[]>([])

const changeQty = (e: any) => {
  for (let key in cartList.value) {
    if (cartList.value[key].productItemId + '' === e.name) {
      cartList.value[key].qty = e.value
    }
  }
  calculateNeedAmount()
}

/** 计算预计金额 */
const calculateNeedAmount = () => {
  let productList = JSON.parse(JSON.stringify(cartList.value))
  formData.value.needAmount = 0
  for (let key in productList) {
    formData.value.needAmount =
      Number(formData.value.needAmount) +
      Number(productList[key].makePrice) * Number(productList[key].qty)
  }
}

/** 删除商品操作 */
const handleDeleteCartList = (row: any) => {
  cartList.value = cartList.value.filter(
    (item: { productItemId: any }) => item.productItemId !== row.productItemId,
  )
  calculateNeedAmount()
}

const submitForm = async (e) => {
  if (query.customerId) {
    formData.value.customerId = query.customerId
  }
  formData.value.productItemList = cartList.value
  if (formData.value.opportunityId) {
    const res = await putOpportunityAPI(formData.value)
  } else {
    const res = await postOpportunityAPI(formData.value)
  }
  navigateBack()
}

const openSelectCus = async () => {
  cusPicker.value!.open()
}

const navigateBack = async () => {
  if (query.fromPage) {
    let pages = getCurrentPages()
    let page: any = pages[pages.length - 2]
    page.$vm.$.exposed.refreshOpportunityList({
      opportunityId: query.opportunityId,
    })
  }
  uni.navigateBack({
    delta: 1,
  })
}

const addProd = async () => {
  prodRef.value!.open()
}

const selectProd = async (data: any) => {
  let isExist = false
  if (cartList.value) {
    for (const j in cartList.value) {
      if (cartList.value[j]['productItemId'] === data['productItemId']) {
        cartList.value[j]['qty']++
        isExist = true
      }
    }
  }
  if (!isExist) {
    cartList.value?.push({
      productItemId: data.productItemId,
      productName: data.productName,
      sku: data.sku,
      imageUrl: data.imageUrl,
      nowPrice: data.nowPrice,
      makePrice: data.nowPrice,
      giveIntegral: data.giveIntegral,
      qty: 1,
      remark: '',
    })
  }
  calculateNeedAmount()
}

const getSaleStageList = async () => {
  let res = await getSaleStageListAPI()
  saleStageList.value = res.data
}

const changeFollowWay = async (e: any) => {
  for (const i in saleStageList.value) {
    if (saleStageList.value[i].saleStageId === e) {
      formData.value.saleStageLabel = saleStageList.value[i].label
    }
  }
  showSaleStage.value = false
}

const getOpportunity = async () => {
  if (query.opportunityId) {
    let res = await getOpportunityAPI(query.opportunityId)
    formData.value = res.data
    cartList.value = formData.value.productItemList
  }
}

// 组件挂载完毕
onMounted(() => {
  open.value = true
  getSaleStageList()
  getOpportunity()
})
</script>

<style lang="scss" scoped>
page {
  background-color: #f7f7f7;
  height: 100%;
}

// 购物车列表
.cart-list {
  padding: 0 20rpx;

  // 优惠提示
  .tips {
    display: flex;
    align-items: center;
    line-height: 1;
    margin: 30rpx 10rpx;
    font-size: 26rpx;
    color: #666;

    .label {
      color: #27ba9b;
      padding: 7rpx 15rpx 5rpx;
      border-radius: 4rpx;
      font-size: 24rpx;
    }
  }

  // 购物车商品
  .goods {
    display: flex;
    padding: 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;
    position: relative;

    .navigator {
      display: flex;
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 20rpx;
    }

    .name {
      height: 72rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrsText {
      line-height: 1.8;
      padding: 0 15rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .price {
      line-height: 1;
      font-size: 26rpx;
      margin-bottom: 2rpx;
      color: #cf4444;

      &::before {
        content: '￥';
        font-size: 80%;
      }
    }

    // 商品数量
    .count {
      position: absolute;
      bottom: 10rpx;
      right: -20rpx;

      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 220rpx;
      height: 48rpx;

      .text {
        height: 100%;
        padding: 0 20rpx;
        font-size: 32rpx;
        color: #444;
      }

      .input {
        height: 100%;
        text-align: center;
        border-radius: 4rpx;
        font-size: 24rpx;
        color: #444;
        background-color: #f6f6f6;
      }
    }
  }

  .cart-swipe {
    display: block;
    margin: 20rpx 0;
  }

  .cart-swipe-right {
    display: flex;
    height: 100%;

    .button {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 50px;
      padding: 6px;
      line-height: 1.5;
      color: #fff;
      font-size: 26rpx;
      border-radius: 0;
    }

    .delete-button {
      background-color: #cf4444;
    }
  }
}
</style>
